package com.zengdada.report.model;

import com.zengdada.authority.model.ReportInfo;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperReport;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.attribute.FileTime;

/**
 * @Auther: 12614
 * @Contact: 1261438511@qq.com
 * @Date: 2019/3/12 16:22
 * @Description:
 */
public class ReportExtend extends ReportInfo {

    JasperReport report;

    FileTime lastModifiedTime;

    Long version;

    public Long getVersion() {
        return version;
    }

    public void setVersion(Long version) {
        this.version = version;
    }

    public JasperReport getReport() {
        return report;
    }

    public void setReport(JasperReport report) {
        this.report = report;
    }

    /**
     * 编译报表文件（存在缓存）
     *
     * @param path 报表文件绝对路径
     * @throws JRException
     * @throws IOException
     */
    public void compile(String path) throws JRException, IOException {
        File file = new File(getLocation());
        if (!file.exists()) file = new File(path);
        if (!file.exists()) file = new ClassPathResource(getLocation()).getFile();
        FileTime lastModifiedTime = Files.getLastModifiedTime(FileSystems.getDefault().getPath(file.getAbsolutePath()));
        if (this.lastModifiedTime != null && this.lastModifiedTime.equals(lastModifiedTime)) {
            return;
        }
        this.report = JasperCompileManager.compileReport(file.getAbsolutePath());
        this.lastModifiedTime = lastModifiedTime;
    }
}
